<template>
  <div id="giftActivity" style="width: 90%">
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="ruleForm"
      label-width="150px"
    >
      <div style="text-align: right">
        <el-button
          @click="goback()"
          size="mini"
          type="primary"
          style="margin-right: 10px"
          >返回</el-button
        >
      </div>
      <el-form-item label="预售活动类型：" prop="activityType">
        <!-- :disabled="!!disabledFlag || ($route.params.edit && !!$route.params.edit.uuid)" -->
        <el-radio-group
          v-model="ruleForm.activityType"
          :disabled="!!disabledFlag"
          @change="changeActivityType"
        >
          <el-radio-button label="1">订金支付</el-radio-button>
          <el-radio-button label="2">全款支付</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="预售活动名称：" prop="activityName">
        <el-input
          type="textarea"
          v-model="ruleForm.activityName"
          :disabled="disabledFlag"
          placeholder="请输入活动名称"
          maxlength="30"
          show-word-limit
          style="width: 250px"
        ></el-input>
      </el-form-item>

      <el-form-item label="活动起止日期：" prop="actTimeRange">
        <el-date-picker
          v-model="ruleForm.actTimeRange"
          type="datetimerange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          :clearable="false"
          :disabled="disabledFlag"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="活动报名时间：" prop="enterDate">
        <el-date-picker
          v-model="ruleForm.enterDate"
          type="datetimerange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          :clearable="false"
          :disabled="disabledFlag"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>

      <el-form-item
        :label="
          ruleForm.activityType == '1' ? '订金支付有效期' : '全款支付有效期'
        "
        prop="runTimeRange"
        :rules="
          ruleForm.activityType == '1'
            ? rules.runTimeRange
            : rules1.runTimeRange1
        "
      >
        <el-date-picker
          v-model="ruleForm.runTimeRange"
          type="datetimerange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          :clearable="false"
          :disabled="disabledFlag"
          :default-time="['00:00:00', '23:59:59']"
          @change="runTimeRangeChange"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="尾款支付有效期："
        :rules="
          ruleForm.activityType == '1'
            ? rules.finalPaymentTimeRange
            : [{ required: false }]
        "
        prop="finalPaymentTimeRange"
        v-show="ruleForm.activityType == '1'"
      >
        <el-date-picker
          v-model="ruleForm.finalPaymentTimeRange"
          type="datetimerange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          :clearable="false"
          :disabled="disabledFlag"
          :default-time="['00:00:00', '23:59:59']"
          @change="finalPaymentTimeRangeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="最晚发货时间：" prop="takeDate">
        <el-date-picker
          v-model="ruleForm.takeDate"
          type="date"
          placeholder="请选择发货时间"
          value-format="yyyy-MM-dd"
          :disabled="disabledFlag"
          style="width: 200px"
        ></el-date-picker>
        开始发货
      </el-form-item>
      <el-form-item
        v-if="ruleForm.activityType == '1'"
        label="商家发货时间："
        prop="merchantSendTime"
      >
        <el-date-picker
          v-model="ruleForm.merchantSendTime"
          type="date"
          placeholder="请选择发货时间"
          value-format="yyyy-MM-dd"
          :disabled="disabledFlag"
          style="width: 200px"
        ></el-date-picker>
        开始发货
      </el-form-item>
      <el-form-item label="目标会员：" prop="memberDTOS">
        <el-checkbox
          :disabled="disabledFlag"
          :checked="item.isChecked"
          v-for="(item, index) in this.memberLevelList"
          :key="index"
          @change="changebox(item)"
          :label="item.memberLevelName"
        >
        </el-checkbox>
      </el-form-item>
      <!--      <el-form-item label="是否可用优惠卷：" prop="isCoupon">-->
      <!--        <el-radio v-model="ruleForm.isCoupon" label="1">是</el-radio>-->
      <!--        <el-radio v-model="ruleForm.isCoupon" label="0">否</el-radio>-->
      <!--      </el-form-item>-->
      <!-- <el-form-item label="预售活动说明：" prop="activityDesc">
				<el-input type="textarea" v-model="ruleForm.activityDesc" :disabled="disabledFlag" placeholder="请输入活动说明"
					maxlength="120" show-word-limit :autosize="{ minRows: 4 }" style="width:650px;"></el-input>
			</el-form-item> -->

      <el-form-item
        label="预售活动说明："
        prop="agreement"
        v-if="!disabledFlag"
      >
        <vue-ueditor-wrap
          id="ue-01"
          v-model="ruleForm.activityDesc"
          :config="myConfig"
          @ready="uEidtready"
          :destroy="true"
        >
        </vue-ueditor-wrap>
      </el-form-item>

      <el-form-item label="预售活动说明：" prop="agreement" v-if="disabledFlag">
        <div class="agreement" v-html="ruleForm.activityDesc"></div>
      </el-form-item>

      <el-form-item
        label="消费者预售协议："
        prop="agreement"
        v-if="!disabledFlag"
      >
        <vue-ueditor-wrap
          id="ue-02"
          v-model="ruleForm.agreement"
          :config="myConfig"
          @ready="uEidtready"
          :destroy="true"
        >
        </vue-ueditor-wrap>
      </el-form-item>

      <el-form-item
        label="消费者预售协议："
        prop="agreement"
        v-if="disabledFlag"
      >
        <div class="agreement" v-html="ruleForm.agreement"></div>
      </el-form-item>

      <el-form-item
        label="虚拟销量"
        prop="virtualSales"
        v-if="ruleForm.activityType == '1'"
      >
        <el-input
          :disabled="disabledFlag"
          v-model="ruleForm.virtualSales"
          placeholder="请输入"
        />
      </el-form-item>

      <el-form-item
        label="活动分享标题"
        prop="eventshareTitle"
        v-if="ruleForm.activityType == '1'"
      >
        <el-input
          :disabled="disabledFlag"
          v-model="ruleForm.eventshareTitle"
          placeholder="请输入"
        />
      </el-form-item>

      <el-form-item
        v-if="ruleForm.activityType == '1'"
        label="活动分享图"
        prop="picurl"
      >
        <el-upload
          :disabled="disabledFlag"
          :action="myConfig.serverUrl"
          :multiple="false"
          :limit="1"
          accept="image/jpeg,image/png"
          list-type="picture-card"
          :on-preview="handlePreview"
          :file-list="fileList"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :on-exceed="handleExceed"
          :headers="headers"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <p class="tips">注：上传图片(限5M) 图片将用于分享图片的展示</p>
      </el-form-item>

      <el-form-item label="活动商品：" prop="goodsCount">
        <el-button
          type="primary"
          @click="showGoodsDialog()"
          icon="el-icon-plus"
          size="mini"
          style="margin: 5px 0 20px 0"
          v-if="!disabledFlag"
          >添加商品
        </el-button>

        <!--商品列表（定金）-->
        <div
          id="giftActivityGoodsTable"
          class="giftTable"
          v-show="ruleForm.activityType == '1'"
        >
          <el-table
            ref="goodsTable"
            :data="goodsDTOS"
            border
            style="width: 100%"
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="goodsSeq"
              column-key="goodsSeq"
              label="商品编码"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="goodsName"
              column-key="goodsName"
              label="商品名称"
              align="center"
            >
            </el-table-column>
            <!-- <el-table-column prop="goodsTypeName" label="商品分类" align="center"></el-table-column> -->
            <el-table-column
              prop="unitName"
              label="计量单位"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="salePriceTemp"
              label="商品标准价"
              header-align="center"
              align="right"
              :formatter="fixData"
              width="120"
            >
            </el-table-column>
            <el-table-column
              prop="depositMoney"
              label="商品预售价"
              header-align="center"
              align="right"
              :formatter="fixData"
              width="100"
            >
              <template slot-scope="scope">
                <span v-if="disabledFlag">
                  {{ scope.row.salePrice.toFixed(2) }}
                </span>
                <el-input
                  :maxlength="8"
                  v-model="scope.row.salePrice"
                  v-if="!disabledFlag"
                  v-on:blur="judgeDepositMoney(scope.row, scope.$index)"
                  style="text-align-last: right"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="优惠方式" width="200" align="center">
              <template slot-scope="scope">
                <el-radio-group
                  :disabled="!!disabledFlag"
                  v-model="scope.row.discountMethod"
                  size="mini"
                >
                  <el-radio-button :label="1">定金膨胀</el-radio-button>
                  <el-radio-button :label="2">定金立减</el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column
              label="定金与优惠"
              header-align="center"
              align="right"
              :formatter="fixData"
              width="160"
            >
              <template slot-scope="scope">
                <div class="flex-mid text-nowrap">
                  定金金额
                  <el-input
                    :maxlength="8"
                    v-model="scope.row.depositMoney"
                    :disabled="disabledFlag"
                    size="small"
                    v-on:blur="
                      judgeDepositMoney(scope.row, scope.$index, 'choice')
                    "
                    style="text-align-last: right"
                  />
                </div>
                <div
                  v-if="scope.row.discountMethod == 1"
                  class="flex-mid text-nowrap"
                >
                  膨胀金额
                  <el-input
                    :maxlength="8"
                    v-model="scope.row.expandMoney"
                    :disabled="disabledFlag"
                    size="small"
                    v-on:blur="judgeExpandMoney(scope.row, scope.$index)"
                    style="text-align-last: right"
                  />
                </div>
                <div
                  v-if="scope.row.discountMethod == 2"
                  class="flex-mid text-nowrap"
                >
                  立减金额
                  <el-input
                    :maxlength="8"
                    v-model="scope.row.reductionMoney"
                    :disabled="disabledFlag"
                    size="small"
                    v-on:blur="judgeDepositMoney(scope.row, scope.$index)"
                    style="text-align-last: right"
                  />
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="expandMoney" v-if="ruleForm.activityType=='1'" label="膨胀金(元)"
							header-align="center" align="right" :formatter="fixData" width="100">
							<template slot-scope="scope">
								<el-input :maxlength="8" v-model="scope.row.expandMoney" :disabled="disabledFlag"
									v-on:blur="judgeExpandMoney(scope.row,scope.$index)" style="text-align-last:right;">
								</el-input>
							</template>
						</el-table-column> -->
            <el-table-column
              width="150"
              prop="buyCount"
              label="单人限购"
              align="center"
              v-if="!disabledFlag"
            >
              <template slot-scope="scope">
                <el-radio-group
                  v-model="scope.row.isLimitQuantity"
                  size="small"
                  @change="changeIsLimitQuantity(scope.row, scope.$index)"
                >
                  >
                  <el-radio-button
                    label="1"
                    class="el-radio-button-inner-child"
                  >
                    <el-input
                      type="number"
                      :min="1"
                      v-model="scope.row.limitQuantity"
                      style="width: 55px; text-align-last: right"
                      v-on:blur="giftSumQuantityCheck(scope.row, scope.$index)"
                    ></el-input>
                  </el-radio-button>
                  <el-radio-button label="0">不限</el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column
              label="单人限购"
              align="center"
              width="150"
              v-if="disabledFlag"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.isLimitQuantity == '1'">{{
                  scope.row.limitQuantity
                }}</span>
                <span v-if="scope.row.isLimitQuantity == '0'">不限</span>
              </template>
            </el-table-column>

            <el-table-column
              width="150"
              prop="amount"
              label="投放数量"
              align="center"
              v-if="!disabledFlag"
            >
              <template slot-scope="scope">
                <el-radio-group
                  v-model="scope.row.isLimit"
                  size="small"
                  @change="changeIsLimitAmount(scope.row, scope.$index)"
                >
                  >
                  <el-radio-button
                    label="1"
                    class="el-radio-button-inner-child"
                  >
                    <el-input
                      type="number"
                      :min="1"
                      v-model="scope.row.amount"
                      style="width: 55px; text-align-last: right"
                      v-on:blur="amountCheck(scope.row, scope.$index)"
                    ></el-input>
                  </el-radio-button>
                  <el-radio-button label="0">不限</el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column>

            <el-table-column
              label="投放数量"
              align="center"
              width="150"
              v-if="disabledFlag"
              prop="amount"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.isLimit == '1'">{{
                  scope.row.amount
                }}</span>
                <span v-if="scope.row.isLimit == '0'">不限</span>
              </template>
            </el-table-column>
            <el-table-column
              label="可售数量"
              prop="currentAmount"
              v-if="disabledFlag"
              align="center"
            >
            </el-table-column>
            <el-table-column
              label="未付款"
              width="140"
              prop="noPayAmount"
              v-if="disabledFlag"
              align="center"
            >
            </el-table-column>
            <el-table-column
              label="已付款"
              width="140"
              v-if="disabledFlag"
              align="center"
            >
              <template slot-scope="scope">
                {{
                  Number(scope.row.amount) -
                    Number(scope.row.currentAmount) -
                    Number(scope.row.noPayAmount)
                }}
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" v-if="!disabledFlag">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="deleteGoodsItem(scope.row, scope.$index)"
                  type="text"
                  >删除商品
                </el-button>
                <!--                <el-button size="mini" @click="showGiftsDialog(scope.row,scope.$index)" type="text">添加赠品</el-button>-->
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!--商品列表 (全款)-->
        <div
          id="giftActivityGoodsTable"
          class="giftTable"
          v-show="ruleForm.activityType == '2'"
        >
          <el-table
            ref="goodsTable"
            :data="goodsDTOS"
            border
            style="width: 100%"
            v-loading="loading"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <el-table-column
              type="index"
              label="序号"
              width="50"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="goodsSeq"
              column-key="goodsSeq"
              label="商品编码"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="goodsName"
              column-key="goodsName"
              label="商品名称"
              align="center"
            >
            </el-table-column>
            <!-- <el-table-column prop="goodsTypeName" label="商品分类" align="center"></el-table-column> -->
            <el-table-column
              prop="unitName"
              label="计量单位"
              align="center"
            ></el-table-column>
            <!-- <el-table-column prop="salePrice" label="商品价格(元)" header-align="center" align="right" 
							:formatter="fixData" width="120" v-if="ruleForm.activityType=='1'"></el-table-column> -->
            <el-table-column
              prop="depositMoney"
              :label="ruleForm.activityType == '1' ? '订金(元)' : '预售价(元)'"
              header-align="center"
              align="right"
              :formatter="fixData"
              width="100"
            >
              <template slot-scope="scope">
                <span v-if="disabledFlag">
                  {{ scope.row.depositMoney.toFixed(2) }}
                </span>
                <el-input
                  :maxlength="8"
                  v-model="scope.row.depositMoney"
                  v-if="!disabledFlag"
                  v-on:blur="judgeDepositMoney(scope.row, scope.$index)"
                  style="text-align-last: right"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column
              prop="expandMoney"
              v-if="ruleForm.activityType == '1'"
              label="膨胀金(元)"
              header-align="center"
              align="right"
              :formatter="fixData"
              width="100"
            >
              <template slot-scope="scope">
                <el-input
                  :maxlength="8"
                  v-model="scope.row.expandMoney"
                  :disabled="disabledFlag"
                  v-on:blur="judgeExpandMoney(scope.row, scope.$index)"
                  style="text-align-last: right"
                >
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              width="150"
              prop="buyCount"
              label="单人限购"
              align="center"
              v-if="!disabledFlag"
            >
              <template slot-scope="scope">
                <el-radio-group
                  v-model="scope.row.isLimitQuantity"
                  size="small"
                  @change="changeIsLimitQuantity(scope.row, scope.$index)"
                >
                  >
                  <el-radio-button
                    label="1"
                    class="el-radio-button-inner-child"
                  >
                    <el-input
                      type="number"
                      :min="1"
                      v-model="scope.row.limitQuantity"
                      style="width: 55px; text-align-last: right"
                      v-on:blur="giftSumQuantityCheck(scope.row, scope.$index)"
                    ></el-input>
                  </el-radio-button>
                  <el-radio-button label="0">不限</el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column>
            <el-table-column
              label="单人限购"
              align="center"
              width="150"
              v-if="disabledFlag"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.isLimitQuantity == '1'">{{
                  scope.row.limitQuantity
                }}</span>
                <span v-if="scope.row.isLimitQuantity == '0'">不限</span>
              </template>
            </el-table-column>

            <el-table-column
              width="150"
              prop="amount"
              label="投放数量"
              align="center"
              v-if="!disabledFlag"
            >
              <template slot-scope="scope">
                <el-radio-group
                  v-model="scope.row.isLimit"
                  size="small"
                  @change="changeIsLimitAmount(scope.row, scope.$index)"
                >
                  >
                  <el-radio-button
                    label="1"
                    class="el-radio-button-inner-child"
                  >
                    <el-input
                      type="number"
                      :min="1"
                      v-model="scope.row.amount"
                      style="width: 55px; text-align-last: right"
                      v-on:blur="amountCheck(scope.row, scope.$index)"
                    ></el-input>
                  </el-radio-button>
                  <el-radio-button label="0">不限</el-radio-button>
                </el-radio-group>
              </template>
            </el-table-column>

            <el-table-column
              label="投放数量"
              align="center"
              width="150"
              v-if="disabledFlag"
            >
              <template slot-scope="scope">
                <span v-if="scope.row.isLimit == '1'">{{
                  scope.row.amount
                }}</span>
                <span v-if="scope.row.isLimit == '0'">不限</span>
              </template>
            </el-table-column>
            <el-table-column
              label="可售数量"
              prop="currentAmount"
              v-if="disabledFlag"
              align="center"
            >
            </el-table-column>
            <el-table-column
              label="未付款"
              width="140"
              prop="noPayAmount"
              v-if="disabledFlag"
              align="center"
            >
            </el-table-column>
            <el-table-column
              label="已付款"
              width="140"
              v-if="disabledFlag"
              align="center"
            >
              <template slot-scope="scope">
                {{
                  Number(scope.row.amount) -
                    Number(scope.row.currentAmount) -
                    Number(scope.row.noPayAmount)
                }}
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" v-if="!disabledFlag">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="deleteGoodsItem(scope.row, scope.$index)"
                  type="text"
                  >删除商品
                </el-button>
                <!--                <el-button size="mini" @click="showGiftsDialog(scope.row,scope.$index)" type="text">添加赠品</el-button>-->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
      <el-form-item label="门店范围：">
        <el-radio-group v-model="ruleForm.isAppoint" :disabled="!!disabledFlag">
          <el-radio-button label="0">通用</el-radio-button>
          <el-radio-button label="1">指定门店</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="适用门店："
        prop="shopList"
        v-if="ruleForm.isAppoint == '1'"
      >
      <!-- YS20250020 -->
        <el-table
          :data="shopList"
          @selection-change="couponShopChecked"
          border
          style="font-size: 10px; width: 100%"
          height="300"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="authCode"
            label="授权码"
            width="180"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="storeName"
            label="店铺名称"
            width="180"
            header-align="center"
          ></el-table-column>
          <el-table-column
            prop="storeOwnerName"
            label="店主姓名"
            width="100"
            header-align="center"
          >
          </el-table-column>
          <el-table-column
            prop="storeAddressDetail"
            label="店铺地址"
            header-align="center"
          ></el-table-column>
        </el-table>
        <div style="margin-top: 10px">
          <el-button
            type="primary"
            @click="selectShop('couponForm')"
            v-if="!disabledFlag"
            >选择门店</el-button
          >
          <el-button @click="deleteShop('couponForm')" v-if="!disabledFlag"
            >删除门店</el-button
          >
        </div>
      </el-form-item>

      <el-form-item label="关联的商品分类：" prop="goodsTypeId">
        <el-radio-group
          style="margin-left: -5px"
          v-model="ruleForm.isRelatedGoodsType"
          :disabled="!!disabledFlag"
          @change="changeIsRelatedGoodsType()"
        >
          <!--          <el-radio-button label="0">不关联</el-radio-button>-->
          <!--          <el-radio-button label="1">关联</el-radio-button>-->
        </el-radio-group>
        <el-select
          style="margin: 7px 0px"
          v-model="ruleForm.goodsTypeId"
          placeholder="请选择"
          v-if="ruleForm.isRelatedGoodsType == 1"
          :disabled="disabledFlag"
          @change="getgoodsTypeId"
        >
          <el-option
            v-for="(send, i) in typeData"
            :key="i"
            :value="send.goodsTypeId"
            :label="send.goodsTypeName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态：">
        <el-radio-group
          v-model="ruleForm.publishStatus"
          :disabled="!!disabledFlag"
        >
          <el-radio-button label="0">不发布</el-radio-button>
          <el-radio-button label="1">发布</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item style="width: 100%; text-align: center">
        <el-button @click="resetForm('ruleForm')" v-show="!this.disabledFlag"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
          v-show="!this.disabledFlag"
          :loading="submitLoading"
          >保存
        </el-button>
      </el-form-item>
    </el-form>

    <!--添加活动商品弹窗-->
    <el-dialog
      title="添加活动商品"
      :visible.sync="insertGoodsDialogVisible"
      width="60%"
    >
      <div>
        <el-form :inline="true" :model="formInline2" class="demo-form-inline">
          <el-row :span="24">
            <el-col :span="24">
              <el-form-item label="商品编码：">
                <el-input
                  v-model="formInline2.goodsSeq"
                  clearable
                  placeholder
                  style="width: 200px"
                >
                </el-input>
              </el-form-item>
              <el-form-item label="商品名称：">
                <el-input
                  v-model="formInline2.goodsName"
                  clearable
                  placeholder
                  style="width: 200px"
                >
                </el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="search2()"
                  size="mini"
                  icon="el-icon-search"
                  >查询
                </el-button>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="kong2()"
                  size="mini"
                  icon="el-icon-delete"
                  >清空
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="table2">
          <el-table
            ref="table2"
            tooltip-effect="dark"
            style="width: 100%"
            v-loading="loading2"
            :data="chooseGoodsList"
            @selection-change="handleSelectionChange2"
            border
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          >
            <el-table-column
              type="selection"
              width="60"
              align="center"
              fixed
              disabled
            ></el-table-column>
            <el-table-column
              type="index"
              label="序号"
              width="60"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="goodsPic"
              label="商品图片"
              align="center"
              width="150"
            >
              <template slot-scope="scope">
                <img
                  :src="scope.row.goodsPic"
                  v-if="scope.row.goodsPic != '' && scope.row.goodsPic != null"
                  width="70"
                  height="50"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="goodsSeq"
              label="商品编码"
              align="center"
              width="150"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="goodsName"
              label="商品名称"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="unitName"
              label="计量单位"
              align="center"
              width="100"
            ></el-table-column>
            <el-table-column
              label="商品描述"
              align="center"
              show-overflow-tooltip
              width="300"
            >
              <template slot-scope="scope">
                <div v-html="scope.row.goodsDescribe"></div>
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="margin-top: 22px; overflow: hidden">
            <el-pagination
              @size-change="handleSizeChange2"
              @current-change="handleCurrentChange2"
              :page-sizes="[10, 20, 30, 50, 100, 150, 200]"
              :current-page="listQuery2.current"
              :page-size="listQuery2.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total2"
            ></el-pagination>
          </div>
          <el-row>
            <el-col :span="24" style="text-align: center; margin-top: 30px">
              <el-button type="info" @click="closeGoodsDialog()" size="mini"
                >取 消
              </el-button>
              <el-button type="primary" @click="insertGoods()" size="mini"
                >确 认
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>

    <el-dialog title="选择门店" :visible.sync="dialogVisibleShop" width="65%">
      <el-form :inline="true" :model="formShop" class="search-form-inline">
        大区：
        <el-select v-model="formShop.warzone">
          <el-option value>全部大区</el-option>
          <el-option
            v-for="item in warzoneList"
            :key="item.orgSeq"
            :label="item.orgName"
            :value="item.orgSeq"
          ></el-option>
        </el-select>
        <el-input
          v-model="formShop.shopName"
          style="width: 200px"
          placeholder="店铺名称"
        ></el-input>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-search"
          @click="getShopList(1)"
          >查询</el-button
        >
      </el-form>
      <el-table
        ref="shopTable"
        :data="orgDTOS"
        border
        style="font-size: 10px; width: 100%"
        height="300"
        @selection-change="shopChecked"
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="authCode"
          label="授权码"
          width="180"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="storeName"
          label="店铺名称"
          width="180"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="storeOwnerName"
          label="店主姓名"
          width="100"
          header-align="center"
        ></el-table-column>
        <el-table-column
          prop="storeAddressDetail"
          label="店铺地址"
          header-align="center"
        ></el-table-column>
      </el-table>
      <div class="block" style="margin-top: 5px">
        <el-pagination
          @size-change="handleSizeChange3"
          @current-change="handleCurrentChange3"
          :page-sizes="[10, 20, 30, 50, 100]"
          :current-page="listQuery.current"
          :page-size="listQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleShop = false">取 消</el-button>
        <el-button type="primary" @click="shopConfirm()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog :visible.sync="dialogVisibleImg" title="图片预览">
      <img width="100%" :src="ruleForm.picurl" />
    </el-dialog>
  </div>
</template>
<script>
import VueUeditorWrap from 'vue-ueditor-wrap';
import {
  addPreSaleAct,
  getActInfoById,
  getWarzoneList,
  qryGoodsTypeList,
  queryChooseGoodsList,
  queryStoreInfo,
  updatePreSaleAct,
  addActivityModificationRecord,
} from '@/api/preSaleActivity';
import { getmemberrule } from '@/api/membergrade';

const curDateStr = function() {
  var curDate = new Date();
  var year = curDate.getFullYear();
  var month = curDate.getMonth() + 1;
  month = month > 9 ? month : '0' + month;
  var date = curDate.getDate();
  date = date > 9 ? date : '0' + date;
  return year + '-' + month + '-' + date;
};

// 定金预售字典
const attrDepositDict = {
  activityName: '预售活动名称',
  beginDate: '活动开始日期',
  endDate: '活动结束日期',
  enterBeginDate: '报名开始日期',
  enterEndDate: '报名结束日期',
  depositBeginDate: '定金支付开始日期',
  depositEndDate: '定金支付结束日期',
  balanceBeginDate: '尾款支付开始日期',
  balanceEndDate: '尾款支付结束日期',
  takeDate: '最晚发货时间',
  merchantSendTime: '商家发货时间',
  activityDesc: '预售活动说明',
  agreement: '消费者预售协议',
  virtualSales: '虚拟销量',
  eventshareTitle: '活动分享标题',
  picurl: '活动分享图',
  goodsTypeId: '关联的商品分类',
  publishStatus: '发布状态',
};
// 全款预售字典
const attrFullPayDict = {
  activityName: '预售活动名称',
  beginDate: '活动开始日期',
  endDate: '活动结束日期',
  enterBeginDate: '报名开始日期',
  enterEndDate: '报名结束日期',
  depositBeginDate: '全款支付开始日期',
  depositEndDate: '全款支付结束日期',
  takeDate: '最晚发货时间',
  activityDesc: '预售活动说明',
  agreement: '消费者预售协议',
  goodsTypeId: '关联的商品分类',
  publishStatus: '发布状态',
};

export default {
  components: {
    VueUeditorWrap,
  },
  data() {
    return {
      headers: {
        token: localStorage.getItem('token'), //从cookie里获取token，并赋值  Authorization ，而不是token
      },
      myConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 240,
        // 初始容器宽度
        initialFrameWidth: '100%',
        // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
        //   serverUrl: 'http://35.201.165.105:8000/controller.php',
        serverUrl: `${process.env.VUE_APP_BASE_API}/api/file-service/v1/file/uploadFile`,
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL:
          process.env.NODE_ENV == 'production'
            ? '../../ui/static/UEditor/'
            : '../../static/UEditor/',
        // UEDITOR_HOME_URL: "../../static/UEditor/"
      },
      formShop: {
        shopName: '',
        warzone: '',
      },
      warzoneList: [],
      checkList: [],
      memberLevelList: [],
      shopList: [],
      orgDTOS: [],
      memberDTOS: [],
      lsShopList: [],
      lsCouponShopList: [],
      disabledFlag: false,
      actflag: false,
      dialogVisibleShop: false,
      insertGoodsDialogVisible: false, //挑选商品弹窗
      typeData: [], //商品类型
      ruleForm: {
        amount: '',
        isLimit: '1',
        limitQuantity: '1',
        isLimitQuantity: '0',
        uuid: null,
        activityCode: '',
        activityType: '1',
        activityName: '',
        actTimeRange: '',
        runTimeRange: '',
        enterDate: '',
        finalPaymentTimeRange: '',
        takeDate: '',
        isCoupon: '0',
        activityDesc: '',
        agreement: '',
        isAppoint: '',
        isRelatedGoodsType: '1',
        goodsTypeId: '',
        goodsTypeName: '',
        publishStatus: '0',
        status: '',
        goodsCount: '', //商品数量
        merchantSendTime: '',
        virtualSales: '',
        eventshareTitle: '',
        picurl: '',
      },
      rules1: {
        runTimeRange1: [
          {
            required: true,
            message: ' 请选择全款支付有效期',
            trigger: 'blur',
          },
        ],
      },
      rules: {
        activityType: [
          {
            required: true,
            message: '请选择预售活动类型',
            trigger: 'blur',
          },
        ],
        activityName: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: 'blur',
          },
        ],

        actTimeRange: [
          {
            required: true,
            message: '请选择活动起止日期',
            trigger: 'blur',
          },
        ],
        enterDate: [
          {
            required: true,
            message: '请选择活动报名日期',
            trigger: 'blur',
          },
        ],
        runTimeRange: [
          {
            required: true,
            message: '请选择订金支付有效期',
            trigger: 'blur',
          },
        ],
        finalPaymentTimeRange: [
          {
            required: true,
            message: '请选择尾款支付有效期',
            trigger: 'blur',
          },
        ],
        takeDate: [
          {
            required: true,
            message: '请选择发货时间',
            trigger: 'blur',
          },
        ],
        activityDesc: [
          {
            required: true,
            message: '请输入活动说明',
            trigger: 'blur',
          },
        ],

        agreement: [
          {
            required: true,
            message: '请填写消费者预售协议',
            trigger: 'blur',
          },
        ],

        goodsCount: [
          {
            required: true,
            message: '请添加活动商品',
            trigger: 'blur',
          },
        ],
        goodsTypeId: [
          {
            required: true,
            message: '请选择商品分类',
            trigger: 'blur',
          },
        ],
        merchantSendTime: [
          {
            required: true,
            message: '请选择商家发货时间',
            trigger: 'blur',
          },
        ],
        virtualSales: [
          {
            required: true,
            message: '请输入虚拟销量',
            trigger: 'blur',
          },
        ],
        eventshareTitle: [
          {
            required: true,
            message: '请输入活动分享标题',
            trigger: 'blur',
          },
        ],
        picurl: [
          {
            required: true,
            message: '请上传活动分享图片',
            trigger: 'change',
          },
        ],
      },
      // 图片预览使用的参数
      dialogVisibleImg: false,
      fileList: [],
      loading: true,
      loading2: true,
      loading3: true,
      listone: [],
      submitLoading: false,
      total: 0,
      total2: 0,
      total3: 0,
      listQuery: {
        current: 1,
        size: 10,
      },
      listQuery2: {
        current: 1,
        size: 10,
      },
      listQuery3: {
        current: 1,
        size: 10,
      },
      sort: '',
      order: '',
      goodsDTOS: [], //商品列表
      chooseGoodsList: [], //挑选商品列表
      batchSelGoods: [], //记录挑选多选商品id
      editGoodsListIndex: '', //记录编辑的商品列表序号
      editGoodsId: '', //记录编辑的商品主键
      editActivityGoodsId: '', //记录编辑的活动商品主键
      chooseGiftsList: [], //挑选赠品列表
      batchSelGifts: [], //记录挑选多选赠品id
      formInline2: {
        goodsName: '',
        goodsSeq: '',
        goodsTypeId: '',
        goodsTypeName: '',
        goodsPic: '',
      }, //查询2
      formInline3: {
        giftName: '',
        giftCode: '',
        giftType: '',
      }, //查询3
      pickerOptions: {
        shortcuts: [
          {
            text: '未来3天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 3);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '未来一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            },
          },
          {
            text: '未来一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            },
          },
        ],
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果当天可选，就不用减8.64e7
        },
      },

      recordInitData: {},
    };
  },
  mounted() {
    this.disabledFlag = !!this.$route.params.flag;
    this.actflag = this.$route.params.actflag;
    var v = this.$route.params.edit;

    this.getProductType(); //加载商品分类

    if (!v) {
      this._getmemberinfo();
      this.loading = false;
      this.ruleForm.isAppoint = '0';
    } else {
      this.getActInfoById(v);
    }
    this.getWarzoneList();
    this.getShopList(1);
  },
  methods: {
    uEidtready(editorInstance) {
      console.log(`编辑器实例${editorInstance.key}: `, editorInstance);
    },
    getgoodsTypeId(v) {
      console.log(v, '8888');
      this.typeData.forEach((item, i) => {
        if (this.typeData[i].goodsTypeId == v)
          console.log(this.typeData[i].goodsTypeName, '999');
        this.ruleForm.goodsTypeName = this.typeData[i].goodsTypeName;
      });
    },

    getWarzoneList() {
      let data = {};
      getWarzoneList(data).then((res) => {
        this.warzoneList = res.records;
      });
    },
    // 查询门店接口
    getShopList(current) {
      let data = {
        size: this.listQuery.size,
        current: current,
        condition: {
          upOrgSeq: this.formShop.warzone,
          storeName: this.formShop.shopName,
        },
        ascs: [],
        descs: [],
      };
      queryStoreInfo(data).then((res) => {
        this.orgDTOS = res.records;
        let arrayList = res.records;
        this.total = res.total;
        // // 去掉已选的
        // this.shopList.forEach(item=>{
        //   arrayList.forEach((orgItem,orgIndex)=>{
        //     if(item.uuid===orgItem.uuid){
        //       console.log("找到了")
        //       this.orgDTOS.splice(orgIndex,1);
        //     }
        //   })
        // })
        console.log('shopList', this.shopList);

        for (var i in this.shopList) {
          this.removeByValue(this.orgDTOS, 'uuid', this.shopList[i].orgSeq);
          this.total -= 1;
          this.total = this.total < 0 ? 0 : this.total;
        }
      });
      // }
      this.loading = false;
    },

    shopChecked(row) {
      this.lsShopList = row;
    },
    shopConfirm() {
      // 保存已选择的门店
      this.dialogVisibleShop = !this.dialogVisibleShop;
      this.shopList = this.shopList.concat(this.lsShopList);
      for (var i in this.lsShopList) {
        this.removeByValue(this.orgDTOS, 'uuid', this.lsShopList[i].uuid);
      }
    },

    selectShop() {
      // 显示选择门店对话框
      this.dialogVisibleShop = !this.dialogVisibleShop;
    },
    couponShopChecked(row) {
      this.lsCouponShopList = row;
    },

    deleteShop() {
      // 删除已选择的门店
      this.orgDTOS = this.orgDTOS.concat(this.lsCouponShopList);
      for (var i in this.lsCouponShopList) {
        this.removeByValue(
          this.shopList,
          'uuid',
          this.lsCouponShopList[i].uuid
        );
      }
    },
    //选择目标会员
    changebox(v) {
      v.isChecked = !v.isChecked;
      // this.memberDTOS = [];
      // if (this.listone.indexOf(v) === -1) {
      //   this.listone.push(v);
      // } else {
      //   this.listone.splice(this.listone.indexOf(v), 1);
      // }
      // console.log(this.listone, "hhrrr");
      //
      //
      // this.listone.forEach((item, i) => {
      //   let data1 = {
      //     memberLevelName: this.listone[i].gradelevelName,
      //     memberLevelId: this.listone[i].memberLevelId
      //   };
      //
      //   this.memberDTOS.push(data1)
      //   console.log(data1, this.memberDTOS, "oooo");
      //
      // });
      //       this.memberDTOS.push(v);
      //     console.log(this.memberDTOS,"oooo");
      // this.memberDTOS.map(o=>{return{memberLevelName:o.gradelevelName, memberLevelId:o.memberLevelId}});
      // console.log(this.memberDTOS,"rrr");
    },

    _getmemberinfo(memberDTOS) {
      let data = {
        size: 10,
        current: 1,
        condition: {},
        ascs: [],
        descs: [],
      };
      getmemberrule(data).then((res) => {
        this.memberLevelList = [];
        res.records.forEach((item, i) => {
          let data1 = {
            memberLevelName: item.gradelevelName,
            memberLevelId: item.uuid,
            isChecked: false,
          };
          this.memberLevelList.push(data1);

          if (memberDTOS && memberDTOS.length != 0) {
            memberDTOS.forEach((dtoItem) => {
              this.memberLevelList.forEach((item) => {
                if (item.memberLevelId == dtoItem.memberLevelId) {
                  item.isChecked = true;
                }
              });
            });
            this.memberLevelList = JSON.parse(
              JSON.stringify(this.memberLevelList)
            );
          } else {
            this.memberLevelList.forEach((item) => {
              item.isChecked = true;
            });
          }
        });
      });
    },
    getProductType(v) {
      let data = {};
      qryGoodsTypeList(data).then((res) => {
        this.typeData = res.result;
      });
    },
    //查询活动详细
    getActInfoById(v) {
      let data = {
        activityId: v.uuid,
      };
      // 修改，回显值
      this.ruleForm.uuid = v.uuid;
      this.ruleForm.activityCode = v.activityCode;
      this.ruleForm.activityType = v.activityType.toString();
      this.ruleForm.activityName = v.activityName;
      this.ruleForm.actTimeRange = [
        v.beginDate.toString(),
        v.endDate.toString(),
      ];
      this.ruleForm.runTimeRange = [
        v.depositBeginDate.toString(),
        v.depositEndDate.toString(),
      ];

      this.ruleForm.enterDate = [v.enterBeginDate, v.enterEndDate];

      if (v.balanceBeginDate && v.balanceEndDate) {
        this.ruleForm.finalPaymentTimeRange = [
          v.balanceBeginDate.toString(),
          v.balanceEndDate.toString(),
        ];
      } else {
        this.ruleForm.finalPaymentTimeRange = ['', ''];
      }

      this.ruleForm.takeDate = v.takeDate;
      this.ruleForm.isCoupon = String(v.isCoupon);
      this.ruleForm.activityDesc = v.activityDesc;
      this.ruleForm.isAppoint = v.isAppoint;
      this.ruleForm.shopList = v.shopList;
      this.ruleForm.isRelatedGoodsType = v.isRelatedGoodsType;
      this.ruleForm.goodsTypeId = v.goodsTypeId == null ? '' : v.goodsTypeId;
      this.ruleForm.goodsTypeName = v.goodsTypeName;
      this.ruleForm.publishStatus = v.publishStatus;
      this.ruleForm.status = v.status;
      this.ruleForm.isLimit = v.isLimit;
      getActInfoById(data).then((res) => {
        if (res.code == 1 && res.result != null) {
          this.loading = false;
          let activityDetail = res.result;
          this.goodsDTOS = activityDetail.goodsDTOS;

          //
          this._getmemberinfo(activityDetail.memberDTOS);

          // activityDetail.memberDTOS.forEach(item => {
          //   this.checkList.push(item.memberLevelName);
          // });
          // this.memberDTOS = [];
          // activityDetail.memberDTOS.forEach((item, i) => {
          //   let data1 = {
          //     memberLevelName: item.memberLevelName,
          //     memberLevelId: item.memberLevelId
          //   };
          //   this.memberDTOS.push(data1);
          //   console.log(this.memberDTOS, "ppuu");
          // });
          this.ruleForm.goodsCount =
            this.goodsDTOS.length == 0 ? '' : this.goodsDTOS.length;
          this.ruleForm.agreement = activityDetail.agreement;

          if (res.result.activityType == 1) {
            this.ruleForm.merchantSendTime = res.result.merchantSendTime;
            this.ruleForm.virtualSales = res.result.virtualSales;
            this.ruleForm.eventshareTitle = res.result.eventshareTitle;
            this.ruleForm.picurl = res.result.picurl;
            res.result.picurl &&
              (this.fileList = [
                {
                  url: res.result.picurl,
                },
              ]);
          }

          if (
            activityDetail.orgDTOS != null &&
            activityDetail.orgDTOS.length > 0
          ) {
            this.shopList = activityDetail.orgDTOS;
          }

          this.recordInitData = { ...v, ...res.result };
        }
      });
    },
    //删除商品行
    deleteGoodsItem(row, index) {
      this.goodsDTOS.splice(index, 1);
      this.ruleForm.goodsCount =
        this.goodsDTOS.length == 0 ? '' : this.goodsDTOS.length;
    },

    /******商品弹窗方法********/
    //显示挑选商品弹窗
    showGoodsDialog() {
      this.formInline2.goodsSeq = '';
      this.formInline2.goodsName = '';
      this.queryChooseGoodsList();
      this.insertGoodsDialogVisible = true;
    },
    //关闭挑选商品弹窗
    closeGoodsDialog() {
      this.insertGoodsDialogVisible = false;
      this.formInline2.goodsSeq = '';
      this.formInline2.goodsName = '';
      this.chooseGoodsList = [];
    },
    //挑选商品列表
    queryChooseGoodsList() {
      let includeGoods = [];
      this.goodsDTOS.forEach((item, index) => {
        includeGoods.push(item.goodsId);
      });
      let data = {
        current: this.listQuery2.current,
        size: this.listQuery2.size,
        condition: {
          activityId: this.ruleForm.uuid,
          includeGoods: includeGoods.length == 0 ? null : includeGoods,
          goodsName: this.formInline2.goodsName.trim(),
          goodsSeq: this.formInline2.goodsSeq.trim(),
          goodsTypeId: this.formInline2.goodsTypeId,
          picUrl: this.formInline2.goodsPic.trim(),
        },
        ascs: [],
        descs: [],
      };
      queryChooseGoodsList(data).then((res) => {
        this.loading2 = false;
        this.chooseGoodsList = res.records;
        this.total2 = res.total;
      });
    },
    handleSizeChange2(val) {
      this.listQuery2.size = val;
      this.queryChooseGoodsList();
    },
    handleCurrentChange2(val) {
      this.listQuery2.current = val;
      this.queryChooseGoodsList();
    },
    //查询挑选商品
    search2() {
      this.listQuery2.current = 1;
      this.queryChooseGoodsList();
    },
    //重置挑选商品
    kong2() {
      this.formInline2.goodsSeq = '';
      this.formInline2.goodsName = '';
      this.formInline2.goodsTypeId = '';
    },
    //监听选择器
    handleSelectionChange2(val) {
      this.batchSelGoods = val;
    },
    //添加商品
    insertGoods() {
      if (this.batchSelGoods.length == 0) {
        this.$message({
          showClose: true,
          message: '请先挑选纳入活动的商品',
          type: 'info',
        });
        return false;
      }
      for (let index = 0; index < this.batchSelGoods.length; index++) {
        let row = this.batchSelGoods[index];
        row.isLimitQuantity =
          row.isLimitQuantity == null ? 0 : row.isLimitQuantity;
        if (row.isLimitQuantity == 0) {
          row.limitQuantity = null;
        }

        let newGoods = {};
        if (this.ruleForm.activityType == '1') {
          //订金预售
          newGoods = {
            uuid: row.activityGoodsId == '' ? null : row.activityGoodsId,
            activityId: this.ruleForm.uuid,
            goodsId: row.uuid,
            goodsSeq: row.goodsSeq,
            goodsName: row.goodsName,
            goodsTypeName: row.goodsTypeName,
            unitName: row.unitName,
            salePrice: row.salePrice,
            depositMoney: row.depositMoney,
            expandMoney: row.expandMoney,
            picUrl: row.goodsPic,
            isLimitQuantity: row.isLimitQuantity,
            buyCount: 1,
            amount: row.amount || 0,
            currentAmount: row.amount || 0,
            isLimit: row.isLimit || '0',
            salePriceTemp: row.salePriceTemp,
            reductionMoney: row.reductionMoney,
          };
        } else if (this.ruleForm.activityType == '2') {
          //全款预售
          newGoods = {
            uuid: row.activityGoodsId == '' ? null : row.activityGoodsId,
            activityId: this.ruleForm.uuid,
            goodsId: row.uuid,
            goodsSeq: row.goodsSeq,
            goodsName: row.goodsName,
            goodsTypeName: row.goodsTypeName,
            unitName: row.unitName,
            salePrice: row.salePrice,
            depositMoney: row.salePrice,
            expandMoney: row.salePrice,
            picUrl: row.goodsPic,
            isLimitQuantity: row.isLimitQuantity,
            buyCount: 1,
            amount: row.amount || 0,
            currentAmount: row.amount || 0,
            isLimit: row.isLimit || '0',
          };
        }
        this.goodsDTOS.splice(0, 0, newGoods);
        this.ruleForm.goodsCount =
          this.goodsDTOS.length == 0 ? '' : this.goodsDTOS.length;
      }
        
      this.closeGoodsDialog();
    },
    /******赠品弹窗方法********/
    //显示挑选赠品弹窗
    showGiftsDialog(row, index) {
      this.editGoodsListIndex = index;
      this.editGoodsId = row.goodsId;
      this.editActivityGoodsId = row.activityGoodsId;
      let $table = this.$refs.goodsTable;
      $table.toggleRowExpansion(row, true);
      this.queryChooseGiftsList();
    },
    handleSizeChange3(val) {
      this.listQuery.size = val;
      this.getShopList(1);
    },
    handleCurrentChange3(val) {
      this.listQuery.current = val;
      this.getShopList(val);
    },
    //监听选择器2
    handleSelectionChange3(val) {
      this.batchSelGifts = val;
    },
    //返回
    goback() {
      this.$router.go('-1');
    },
    //取消
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$router.push('preSaleActivityManage');
    },
    //保存活动
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.memberDTOS = [];
          this.memberLevelList.forEach((item) => {
            if (item.isChecked) {
              this.memberDTOS.push(item);
            }
          });

          if (this.goodsDTOS == null || this.goodsDTOS.length == 0) {
            this.$message({
              showClose: true,
              message: '活动商品不能为空',
              type: 'info',
            });
            return;
          }

          if (this.memberDTOS == null || this.memberDTOS.length == 0) {
            this.$message({
              showClose: true,
              message: '请选择目标会员',
              type: 'info',
            });
            return;
          }

          if (
            this.ruleForm.enterDate != null &&
            this.ruleForm.enterDate.length == 2
          ) {
            this.ruleForm.enterBeginDate = this.ruleForm.enterDate[0];
            this.ruleForm.enterEndDate = this.ruleForm.enterDate[1];
          }

          if (
            this.ruleForm.actTimeRange != null &&
            this.ruleForm.actTimeRange.length == 2
          ) {
            this.ruleForm.beginDate = this.ruleForm.actTimeRange[0];
            this.ruleForm.endDate = this.ruleForm.actTimeRange[1];
          }

          if (
            this.ruleForm.runTimeRange != null &&
            this.ruleForm.runTimeRange.length == 2
          ) {
            this.ruleForm.depositBeginDate = this.ruleForm.runTimeRange[0];
            this.ruleForm.depositEndDate = this.ruleForm.runTimeRange[1];
          }

          if (
            this.ruleForm.finalPaymentTimeRange != null &&
            this.ruleForm.finalPaymentTimeRange.length == 2
          ) {
            this.ruleForm.balanceBeginDate = this.ruleForm.finalPaymentTimeRange[0];
            this.ruleForm.balanceEndDate = this.ruleForm.finalPaymentTimeRange[1];
          }

          if (
            this.ruleForm.depositBeginDate < this.ruleForm.beginDate ||
            this.ruleForm.depositBeginDate > this.ruleForm.endDate ||
            this.ruleForm.depositEndDate < this.ruleForm.beginDate ||
            this.ruleForm.depositEndDate > this.ruleForm.endDate
          ) {
            this.$message({
              showClose: true,
              message:
                this.ruleForm.activityType == '1'
                  ? '订金支付时间超出活动范围，请重新选择！'
                  : '付款有效时间超出活动范围，请重新选择！',
              type: 'info',
            });
            this.ruleForm.runTimeRange = '';
            return;
          }

          //非全款预售才校验
          if (this.ruleForm.activityType == '1') {
            if (
              this.ruleForm.balanceBeginDate < this.ruleForm.beginDate ||
              this.ruleForm.balanceBeginDate > this.ruleForm.endDate ||
              this.ruleForm.balanceEndDate < this.ruleForm.beginDate ||
              this.ruleForm.balanceEndDate > this.ruleForm.endDate
            ) {
              this.$message({
                showClose: true,
                message: '尾款支付时间超出活动范围，请重新选择！',
                type: 'info',
              });
              this.ruleForm.finalPaymentTimeRange = '';
              return;
            }

            if (
              this.ruleForm.balanceBeginDate < this.ruleForm.depositBeginDate ||
              this.ruleForm.balanceBeginDate < this.ruleForm.depositBeginDate ||
              this.ruleForm.balanceEndDate < this.ruleForm.depositEndDate ||
              this.ruleForm.balanceEndDate < this.ruleForm.depositEndDate
            ) {
              this.$message({
                showClose: true,
                message: '尾款支付时间应在订金支付时间之后，请重新选择！',
                type: 'info',
              });
              this.ruleForm.finalPaymentTimeRange = '';
              return;
            }

            if (this.ruleForm.eventshareTitle == '') {
              this.$message({
                showClose: true,
                message: '请输入分享活动标题',
                type: 'info',
              });
              return;
            }
          }

          if (this.ruleForm.takeDate == '' || this.ruleForm.takeDate == null) {
            this.$message.error('请输入提货时间');
            return;
          }
          if (
            this.ruleForm.isAppoint != '0' &&
            this.ruleForm.isAppoint != '1'
          ) {
            this.$message.error('请选择门店范围');
            return;
          }
          if (
            this.ruleForm.isAppoint == '1' &&
            (this.shopList == null || this.shopList.length == 0)
          ) {
            this.$message.error('请选择门店');
            return;
          }

          const isSalePrice = this.goodsDTOS.some((item) => {
            return item.salePrice < 1;
          });

          if(isSalePrice) {
            this.$message.error('预售价不能小于1');
            return;
          }

          let goodsDTOS = this.goodsDTOS;
          if (this.ruleForm.activityType == '2') {
            //全款预售 膨胀金等于预售金额
            goodsDTOS.forEach((item) => {
              item.expandMoney = item.depositMoney;
              item.currentAmount = item.amount;
            });
          }

          let data = {
            uuid: this.ruleForm.uuid,
            activityType: this.ruleForm.activityType,
            activityName: this.ruleForm.activityName,
            enterBeginDate: this.ruleForm.enterBeginDate,
            enterEndDate: this.ruleForm.enterEndDate,
            beginDate: this.ruleForm.beginDate,
            endDate: this.ruleForm.endDate,
            depositBeginDate: this.ruleForm.depositBeginDate,
            depositEndDate: this.ruleForm.depositEndDate,
            balanceBeginDate: this.ruleForm.balanceBeginDate,
            balanceEndDate: this.ruleForm.balanceEndDate,
            takeDate: this.ruleForm.takeDate,
            activityDesc: this.ruleForm.activityDesc,
            isCoupon: this.ruleForm.isCoupon,
            isAppoint: this.ruleForm.isAppoint,
            isRelatedGoodsType: this.ruleForm.isRelatedGoodsType,
            goodsTypeId: this.ruleForm.goodsTypeId,
            goodsTypeName: this.ruleForm.goodsTypeName,
            publishStatus: this.ruleForm.publishStatus,
            goodsDTOS,
            memberDTOS: this.memberDTOS,
            orgDTOS: this.shopList,
            agreement: this.ruleForm.agreement,
            merchantSendTime: this.ruleForm.merchantSendTime,
            virtualSales: this.ruleForm.virtualSales,
            eventshareTitle: this.ruleForm.eventshareTitle,
            picurl: this.ruleForm.picurl,
          };
          console.log('data', data);
          this.submitLoading = true;
          if (this.actflag == true) {
            addPreSaleAct(data).then((res) => {
              if (res.code == 1) {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'success',
                });
                //this.submitLoading = false;
                this.$router.push('preSaleActivityManage');
              } else {
                this.submitLoading = false;
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'error',
                });
              }
            });
          } else {
            //修改
            const recordValue = this.recordChangeValue(
              this.ruleForm.activityType
            );
            addActivityModificationRecord(recordValue).then((res) => {
              if (res.code == 1) {
                this.$message({
                  showClose: true,
                  message: `记录修改值${res.message}`,
                  type: 'success',
                });
              } else {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'error',
                });
                this.submitLoading = false;
              }
            });

            updatePreSaleAct(data).then((res) => {
              if (res.code == 1) {
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'success',
                });
                //this.submitLoading = false;
                this.$router.push('preSaleActivityManage');
              } else {
                this.submitLoading = false;
                this.$message({
                  showClose: true,
                  message: res.message,
                  type: 'error',
                });
              }
            });
          }
        } else {
        }
      });
    },

    /**
     * @description: 记录修改的值
     * @param {Number} activityType 用于区分是定金预售还是全款预售
     * @return {Array} 返回变动的值
     */
    recordChangeValue(activityType) {
      const attrDict = activityType == 1 ? attrDepositDict : attrFullPayDict;
      const recordValue = [];
      Object.keys(attrDict).forEach((key) => {
        if (this.recordInitData[key] != this.ruleForm[key]) {
          recordValue.push({
            activityCode: this.ruleForm.activityCode,
            activityName: this.ruleForm.activityName,
            originalValue: `${attrDict[key]}：${this.recordInitData[key]}`,
            editValue: `${attrDict[key]}：${this.ruleForm[key]}`,
          });
        }
      });

      return recordValue;
    },

    //判断订金支付时间
    runTimeRangeChange() {
      let val = this.ruleForm.actTimeRange;
      let runVal = this.ruleForm.runTimeRange;
      var actBegin = '';
      var actEnd = '';
      if (
        val != null &&
        val.length == 2 &&
        runVal != null &&
        runVal.length == 2
      ) {
        actBegin = val[0];
        actEnd = val[1];
        if (
          runVal[0] < actBegin ||
          runVal[0] > actEnd ||
          runVal[1] < actBegin ||
          runVal[1] > actEnd
        ) {
          this.$message({
            showClose: true,
            message: '订金支付时间超出活动范围，请重新选择！',
            type: 'info',
          });
          this.ruleForm.runTimeRange = '';
        }
      }
    },
    //判断尾款支付时间
    finalPaymentTimeRangeChange() {
      let val = this.ruleForm.actTimeRange;
      let runVal = this.ruleForm.finalPaymentTimeRange; //尾款
      let beginVal = this.ruleForm.runTimeRange; //订金时间
      var actBegin = '';
      var actEnd = '';
      if (
        val != null &&
        val.length == 2 &&
        runVal != null &&
        runVal.length == 2
      ) {
        actBegin = val[0];
        actEnd = val[1];
        if (
          runVal[0] < actBegin ||
          runVal[0] > actEnd ||
          runVal[1] < actBegin ||
          runVal[1] > actEnd
        ) {
          this.$message({
            showClose: true,
            message: '尾款支付时间超出活动范围，请重新选择！',
            type: 'info',
          });
          this.ruleForm.finalPaymentTimeRange = '';
        }
      }
      if (
        runVal != null &&
        runVal.length == 2 &&
        beginVal != null &&
        beginVal.length == 2
      ) {
        if (
          runVal[0] < beginVal[0] ||
          runVal[0] < beginVal[1] ||
          runVal[1] < beginVal[0] ||
          runVal[1] < beginVal[1]
        ) {
          this.$message({
            showClose: true,
            message: '尾款支付时间应在订金支付时间之后，请重新选择！',
            type: 'info',
          });
          this.ruleForm.finalPaymentTimeRange = '';
        }
      }
    },
    //修改是否关联商品类型
    changeIsRelatedGoodsType() {
      if (this.ruleForm.isRelatedGoodsType == 0) {
        this.ruleForm.goodsTypeId = null;
        this.ruleForm.goodsTypeName = null;
      }
    },
    //修改个人限购选择
    changeIsLimitQuantity(row, index) {
      if (row.isLimitQuantity == 0) {
        //不限
        this.goodsDTOS[index].isLimitQuantity = 0;
        this.goodsDTOS[index].limitQuantity = null;
      } else if (
        row.limitQuantity === null ||
        row.limitQuantity === undefined ||
        row.limitQuantity === ''
      ) {
        this.goodsDTOS[index].limitQuantity = 1;
        this.goodsDTOS[index].isLimitQuantity = 1;
      }
    },
    //库存限量选择
    changeIsLimitAmount(row, index) {
      if (row.isLimit == 0) {
        //不限
        this.goodsDTOS[index].isLimit = 0;
        this.goodsDTOS[index].amount = null;
      } else if (
        row.amount === null ||
        row.amount === undefined ||
        row.amount === ''
      ) {
        this.goodsDTOS[index].amount = 1;
        this.goodsDTOS[index].isLimit = 1;
      }
    },
    //购买数量校验
    buyCountCheck(row, index) {
      let val = row.buyCount;
      if (val === null || val === undefined || val === '') {
        this.$message({
          showClose: true,
          message: '填入数量不能为空',
          type: 'info',
        });
        val = 1;
      } else if (isNaN(val)) {
        this.$message({
          showClose: true,
          message: '填入数量格式错误',
          type: 'info',
        });
        val = 1;
      } else if (val < 1) {
        this.$message({
          showClose: true,
          message: '填入数量应大于等于1',
          type: 'info',
        });
        val = 1;
      }
      this.goodsDTOS[index].buyCount = parseInt(val);
      return true;
    },
    judgeDepositMoney(row, index, type) {
      if (type == 'choice' && !row.discountMethod) {
        this.$message({
          showClose: true,
          message: '请选择优惠方式',
          type: 'info',
        });
        return false;
      }

      if (this.ruleForm.activityType == '1') {
        let val = row.depositMoney;
        let flag = new RegExp(
          '(^[1-9]([0-9]+)?(.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9].[0-9]([0-9])?$)'
        ).test(val);
        if (val === null || val === undefined || val === '') {
          this.$message({
            showClose: true,
            message: '填入订金不能为空',
            type: 'info',
          });
        } else if (!flag) {
          this.$message({
            showClose: true,
            message: '填入订金格式错误',
            type: 'info',
          });
        } else if (val < 1) {
          this.$message({
            showClose: true,
            message: '填入订金应大于等于1',
            type: 'info',
          });
        } else {
          if (Number(row.salePrice) < Number(val)) {
            this.$message({
              showClose: true,
              message: '填入订金不能大于商品价格',
              type: 'info',
            });
          }
        }
        this.goodsDTOS[index].depositMoney = val;
        return true;
      } else {
        let val = row.depositMoney;
        let flag = new RegExp(
          '(^[1-9]([0-9]+)?(.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9].[0-9]([0-9])?$)'
        ).test(val);
        if (val === null || val === undefined || val === '') {
          this.$message({
            showClose: true,
            message: '填入预售价不能为空',
            type: 'info',
          });
        } else if (!flag) {
          this.$message({
            showClose: true,
            message: '填入预售价格式错误',
            type: 'info',
          });
        } else if (val < 1) {
          this.$message({
            showClose: true,
            message: '填入预售价应大于等于1',
            type: 'error',
          });
        }
        // else {
        // 	if (Number(row.salePrice) < Number(val)) {
        // 		this.$message({
        // 			showClose: true,
        // 			message: "填入订金不能大于商品价格",
        // 			type: "info"
        // 		});
        // 		val = 1;
        // 	}
        // }
        this.goodsDTOS[index].salePrice = val;
        return true;
      }
    },
    judgeExpandMoney(row, index) {
      let val = row.expandMoney;
      let flag = new RegExp(
        '(^[1-9]([0-9]+)?(.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9].[0-9]([0-9])?$)'
      ).test(val);
      if (val === null || val === undefined || val === '') {
        this.$message({
          showClose: true,
          message: '填入膨胀金不能为空',
          type: 'info',
        });
        val = '';
      } else if (!flag) {
        this.$message({
          showClose: true,
          message: '填入膨胀金格式错误',
          type: 'info',
        });
        val = '';
      } else if (val < 1) {
        this.$message({
          showClose: true,
          message: '填入膨胀金应大于等于1',
          type: 'info',
        });
        val = '';
      } else {
        if (Number(row.salePrice) <= Number(val)) {
          this.$message({
            showClose: true,
            message: '填入膨胀金不能大于等于商品价格',
            type: 'info',
          });
          val = '';
        } else if (Number(row.depositMoney) > Number(val)) {
          this.$message({
            showClose: true,
            message: '填入膨胀金不能小于订金',
            type: 'info',
          });
          val = '';
        }
      }
      this.goodsDTOS[index].expandMoney = val;
      return true;
    },
    //校验限购数量
    giftSumQuantityCheck(row, index) {
      let val = row.limitQuantity;
      if (val === null || val === undefined || val === '') {
        this.$message({
          showClose: true,
          message: '填入数量不能为空',
          type: 'info',
        });
        val = 1;
      } else if (isNaN(val)) {
        this.$message({
          showClose: true,
          message: '填入数量格式错误',
          type: 'info',
        });
        val = 1;
      } else if (val < 1) {
        this.$message({
          showClose: true,
          message: '填入数量应大于等于1',
          type: 'info',
        });
        val = 1;
      }
      this.goodsDTOS[index].limitQuantity = parseInt(val);
      this.goodsDTOS[index].isLimitQuantity = 1;
      return true;
    },
    //库存填写校验
    amountCheck(row, index) {
      let val = row.amount;
      if (val === null || val === undefined || val === '') {
        this.$message({
          showClose: true,
          message: '填入数量不能为空',
          type: 'info',
        });
        val = 1;
      } else if (isNaN(val)) {
        this.$message({
          showClose: true,
          message: '填入数量格式错误',
          type: 'info',
        });
        val = 1;
      } else if (val < 1) {
        this.$message({
          showClose: true,
          message: '填入数量应大于等于1',
          type: 'info',
        });
        val = 1;
      }
      this.goodsDTOS[index].amount = parseInt(val);
      this.goodsDTOS[index].isLimit = 1;
      return true;
    },

    fixData(row, column, cellValue, index) {
      if (cellValue != null && !isNaN(cellValue)) {
        return cellValue.toFixed(2);
      } else {
        return cellValue;
      }
    },

    // 数组，属性，属性值
    removeByValue: function(arr, attr, value) {
      if (arr == null) {
        return;
      }
      var type = 0;
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          type = 1;
          break;
        }
      }
      if (type == 1) {
        arr.splice(index, 1);
      }
    },

    // 活动分享图片相关函数
    handlePreview(file) {
      !this.ruleForm.picurl && (this.ruleForm.picurl = file.url);
      this.dialogVisibleImg = true;
    },
    handleRemove(file) {
      this.ruleForm.picurl = '';
    },
    handleSuccess(response) {
      this.ruleForm.picurl = response.result;
    },
    handleExceed() {
      this.$message.error('图片最多上传1张');
    },

    changeActivityType() {
      this.goodsDTOS = [];
    }
  },
};
</script>
<style lang="scss" scoped>
#giftActivity /deep/ .giftTable table th,
#giftActivity .giftTable table td {
  border: 1px solid #ebeef5;
}

#giftActivity /deep/ .giftTable table th {
  background: #eef1f6;
  color: #606266;
}

#giftActivity
  /deep/
  .giftTable
  table
  .el-radio-button-inner-child
  .el-radio-button__inner {
  padding: 0;
}

#giftActivity
  /deep/
  .giftTable
  table
  .el-radio-button-inner-child
  .el-input__inner {
  border: none;
  height: 30px;
}

#giftActivity /deep/ .el-dialog__body {
  padding-top: 0px;
}

#giftActivityGoodsTable /deep/ .el-input__inner[type='number'] {
  padding: 0;
}

.agreement {
  width: 80%;
  height: 200px;
  overflow: auto;
  padding: 20px;
  background: #ebeef5;
  border-radius: 5px;
}

.flex-mid {
  display: flex;
  align-items: center;
  &.text-nowrap {
    gap: 4px;
    white-space: nowrap;
  }
  &:not(:first-child) {
    margin-top: 8px;
  }
}
</style>
